package xin.marcher.module.message.mq.consumer.listener;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xin.marcher.module.common.domain.TraceData;
import xin.marcher.module.common.enums.message.BinlogType;
import xin.marcher.module.common.utils.message.BinlogUtils;
import xin.marcher.module.message.service.MessageService;

import java.util.List;

/**
 *
 */
@Slf4j
@Component
public class DataTraceListener implements MessageListenerConcurrently {

    @Autowired
    private MessageService messageService;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
            for (MessageExt messageExt : list) {
                String msg = new String(messageExt.getBody());
                log.info("DataTraceListener数据变更消息通知，消息内容：{}", msg);

                JSONObject jsonObject = JSONUtil.parseObj(msg);
                // 操作类型
                String operateType = jsonObject.getStr("type");
                if (!BinlogType.INSERT.getValue().equals(operateType)
                        && !BinlogType.DELETE.getValue().equals(operateType)
                        && !BinlogType.UPDATE.getValue().equals(operateType)) {
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
                // ddl
                if (jsonObject.getBool("isDdl")) {
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }

                // 把消息解析成TraceData对象
                List<TraceData> traceDataList = BinlogUtils.getTraceData(msg);
                if (CollectionUtils.isEmpty(traceDataList)) {
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }

                // 处理消息
                messageService.processTraceMessage(traceDataList);

            }
        } catch (Exception e) {
            log.error("DataTraceListener consume error, 消费数据变更消息失败", e);
            // 本次消费失败，下次重新消费
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }

        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

}
